package cn.circle.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.circle.system.model.CommodityInfo;
import cn.circle.commom.controller.BackendBaseController;
import cn.circle.system.service.ICommodityInfoService;
import cn.circle.system.pagemodel.DataGrid;
import cn.circle.system.pagemodel.PageHelper;
import cn.circle.system.pagemodel.ReturnInfo;
import cn.circle.system.util.FileUploadUtil;
import cn.circle.system.util.FtpUtil;
import cn.circle.system.util.IDUtils;

/**
 * 
 * 作者
 */

@Controller
@RequestMapping("/manage/commodity")
public class CommodityInfoController extends BackendBaseController {
	private static final Log log = LogFactory.getLog(CommodityInfoController.class);
	@Autowired
	private ICommodityInfoService commodityInfoService;

	/**
	 * 
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request) {

		return super.index("/WEB-INF/pages/system/commodity/commodity_list.jsp", request);
	}

	/**
	 * 查询商品信息
	 */
	@ResponseBody
	@RequestMapping(value = "/dataGrid")
	public DataGrid dataGrid(@ModelAttribute CommodityInfo c, PageHelper ph, HttpServletRequest request, Integer sort,
			Double _price, Double price_) {
		String sortType = "createTime";
		if (sort != null && !"".equals(sort)) {
			switch (sort) {
			case 1:
				sortType = "price";
				break;
			case 2:
				sortType = "number";
				break;
			case 3:
				sortType = "viewCount";
				break;
			case 4:
				sortType = "orderCount";
				break;
			default:
				sortType = "createTime";
				break;
			}
		}

		ph.setSort(sortType);
		ph.setOrder("desc");
	/*	DataGrid dg = commodityInfoService.datagrid(ph, c, getUserDepId(request), _price, price_);*/
		DataGrid dg = commodityInfoService.datagrid(ph,c, _price, price_);
		return dg;
	}

	/**
	 * 跳转至 sysmenus_au页(添加和修改共用一个编辑页)
	 */
	@RequestMapping(value = "/add")
	public String add(Map<String, Object> map) {

		map.put("saveUrl", "/manage/commodity/addSave");
		return "/WEB-INF/pages/system/commodity/commodity_au.jsp";
	}

	/**
	 * 保存添加数据
	 */
	@ResponseBody
	@RequestMapping(value = "/addSave")
	public ReturnInfo addSave(@Valid CommodityInfo commodityInfo, BindingResult b, ReturnInfo result,
			@RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {

		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getField() + "" + error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (commodityInfo != null) {
				
				try {
					Date date = new Date();
					java.sql.Timestamp passSqlDate = new java.sql.Timestamp(date.getTime());
					commodityInfo.setCreateTime(passSqlDate);
					commodityInfoService.save(commodityInfo, file);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return result;
	}

	/**
	 * 显示
	 */
	@RequestMapping(value = "/view")
	public String view(String id, Map<String, Object> map) {

		if (id != null) {
			List<CommodityInfo> model = commodityInfoService.getUser(id);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/pages/system/commodity/commodity_view.jsp";
	}

	/**
	 * 跳转至 sysmenus_au页
	 */
	@RequestMapping(value = "/edit")
	public String edit(String id, Map<String, Object> map) {
		map.put("saveUrl", "/manage/commodity/editSave");

		if (id != null) {
			List<CommodityInfo> model = commodityInfoService.getUser(id);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/pages/system/commodity/commodity_au.jsp";
	}

	/**
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/editSave")
	public ReturnInfo editSave(@Valid CommodityInfo commodityInfo, BindingResult b, ReturnInfo result,
			@RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		System.out.println(commodityInfo.getCommodityId());

		if (b.getErrorCount() > 0) { // 数据校验
			log.info("数据校验出错！");
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getField() + "" + error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (commodityInfo != null) {
				
				try {
					commodityInfoService.update(commodityInfo,file);
				} catch (Exception e) {
					// TODO: handle exception
					log.info("" + e.getMessage());
					result.setMsg("修改失败！");
					result.setSuccess(1);
				}

			}
		}

		return result;
	}

	/**
	 * 物理删除,从数据库中删除
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public ReturnInfo delete(String ids, ReturnInfo result) {
		if (ids != null) {
			try {
				commodityInfoService.deleteAll(ids);
			} catch (Exception e) {
				log.info("删除异常" + e.getMessage());
				result.setMsg("删除失败！");
				result.setSuccess(1);
			}
		}
		return result;
	}

	/**
	 * 移除,逻辑删除
	 */
	@ResponseBody
	@RequestMapping(value = "/remove")
	public ReturnInfo remove(String ids, ReturnInfo result) {
		if (ids != null) {
			try {
				commodityInfoService.removeAll(ids);
			} catch (Exception e) {
				log.info("移除异常" + e.getMessage());
				result.setMsg("移除失败！");
				result.setSuccess(1);
			}
		}
		return result;
	}

	/**
	 * 跳转到回收站界面
	 */

	@RequestMapping(value = "/recycle")
	public String recycle() {

		return "";
	}

	/**
	 * 获取状态为0的数据显示到回收站中
	 */
	@RequestMapping(value = "/recycleDate")
	public String recycleDate() {

		return "";
	}

	/**
	 * 恢复回收站的内容，将其状态修改为9
	 */
	@RequestMapping(value = "/recovery")
	public String recovery() {

		return "";
	}

	/**
	 * 根据提供的名称获得单个resources目录下config.properties属性值 方法一(不能静态.....)
	 * 
	 * @author 
	 */
	public String getConfigAttr(String str) {

		String attrStr = null;
		Properties prop = new Properties();
		InputStream is = this.getClass().getResourceAsStream("/config.properties");
		try {
			prop.load(is);
			attrStr = prop.getProperty(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return attrStr;

	}

}
